const httpRequest = {};
/**
 * common 云函数 方法 3 
 * 获取配置店铺实例化信息
 *
 * @param {String} sellerId 店铺 sellerId
 * @returns {Object} 结果信息对象
 */
 httpRequest.getShopInfo = async (sellerId = '') => {
  return new Promise(async (resolve, reject) => {
    const requestResultName = "查询配置店铺实例化信息";
    const options = {
      data: {
        sellerId
      },
      handler: 'findShopOne'
    };

    try {
      let res = await miniInterfaceRequest(options, requestResultName);
      const result = JSON.parse(JSON.stringify(res.data))
      // 将店铺信息放在全局
      const shopInfo = result;
      $global.shopInfo = shopInfo;
      $global.mfutil.logger.log(`${JSON.stringify(shopInfo)}`, 'shopInfo');
      resolve({ state: true, msg: ` ${requestResultName} 成功`, data: shopInfo })
    } catch (err) {
      reject({ state: false, msg: `处理 ${requestResultName} catch 异常` + JSON.stringify(err) })
    }
  })
}
/**
 * common 云应用方法 2 
 * configs配置信息
 * 
 * @param { Array } keys   -->参考config文件
 * @returns {Object} 结果信息对象
 */
 httpRequest.getConfigsInfo = async (keys) => {
  return new Promise(async (resolve, reject) => {
    const requestResultName = "查询configs 配置信息";
    const options = {
      data: {
        httUrl: '/configs/v2',
        mothed: 'POST',
        parms: {
          keys
        }
      },
    };

    try {
      let res = await interfaceRequest(options, requestResultName);
      const result = JSON.parse(res.data)
      if (result.success) {
        const configInfo = result.data;
        resolve({ state: true, msg: ` ${requestResultName}`, data: configInfo })
      } else {
        resolve({ state: true, msg: ` ${requestResultName}: fail`, data: {} })
      }
    } catch (err) {
      console.log(err,'=====err')
      reject({ state: false, msg: `处理 ${requestResultName} catch 异常` + JSON.stringify(err) })
    }
  })
}


//云应用api请求
const interfaceRequest = async function (obj, requestResultName) {
  return new Promise(async (resolve, reject) => {
    try {
      // 参数处理结果正常后调用云应用接口
      const cloudResult = await cloudApplication(obj);
      //阿里云网关请求正常
      if (cloudResult && cloudResult.code == 200) {
        // console.log(`interfaceRequest ============== : ${requestResultName}`, cloudResult)
        resolve(cloudResult);
      } else {
        reject({ state: false, msg: `请求 ${requestResultName} 失败` + JSON.stringify(cloudResult) })
        $global.mfutil.logger.log(`请求 ${requestResultName} 失败` + JSON.stringify(cloudResult), 'interfaceRequest');
      }
    } catch (err) {
      reject({ state: false, msg: `请求 ${requestResultName} catch 异常` + JSON.stringify(err) })
      $global.mfutil.logger.log(`请求 ${requestResultName} catch 异常` + JSON.stringify(err), 'interfaceRequest');
    }
  })
}

/**
 * 公共方法 : 调用云应用
 * @param {Object} obj 请求数据 
 * @param {Object} data 请求数据 
 * @param {String} url 请求数据 
 * @param {Object} exts 请求数据 
 * @param {Object} data 请求参数 
 * 
 * @returns 结果信息
 */
const cloudApplication = async function (options) {
  const { data = { mothed: 'post' }, url = '/base/send', exts = {} } = options;
  // console.log('=======data=======', data)
  // ---> 请求参数带上店铺 id 和 店铺 sellerId ： get 请求
  if (data.mothed == 'GET' && data.httUrl) {
    let tag = data.httUrl.indexOf('?') > -1 ? '&' : '?'
    data.httUrl = data.httUrl + tag + 'store=' + $global.shopInfo.shopId
    data.httUrl = data.httUrl + '&' + 'seller_id=' + $global.shopInfo.sellerId
    data.httUrl = data.httUrl + '&' + 'shop_id=' + $global.shopInfo.shopId
  }
  // ---> 请求参数带上店铺 id 和 店铺 sellerId ： post 请求
  if (data.parms) {
    data.parms.store = $global.shopInfo.shopId + ''
    data.parms.seller_id = $global.shopInfo.sellerId + ''
    data.parms.shop_id = $global.shopInfo.shopId + ''
  }
  // console.log('-----> cloudApplication - data: ', data)
  // ---> 请求结果

  return new Promise((resolve, reject) => {
    $global.cloud.application.httpRequest({
      'path': url,
      'method': 'POST',
      'headers': { "Content-Type": "application/json;charset=UTF-8" },
      'params': {},
      'body': JSON.stringify({ traceId: $global.config.traceId, ...data }),
      'exts': { "cloudAppId": $global.config.cloudAppId, "timeout": 10000, ...exts }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
      console.log(err,'======')
    })
  })
}
//云函数api请求
const miniInterfaceRequest = async function (obj, requestResultName) {
  return new Promise(async (resolve, reject) => {
    try {
      // 参数处理结果正常后调用云函数接口
      const cloudResult = await cloudInvoke(obj);
      //阿里云网关请求正常
      if (cloudResult && cloudResult.code == 200) {
        // console.log(`miniInterfaceRequest ============== : ${requestResultName}`, cloudResult)
        resolve(cloudResult);
      } else {
        reject({ state: false, msg: `请求 ${requestResultName} 失败` + JSON.stringify(cloudResult) })
        $global.mfutil.logger.log(`请求 ${requestResultName} 失败` + JSON.stringify(cloudResult), 'interfaceRequest');
      }
    } catch (err) {
      console.log(err,'=====')
      reject({ state: false, msg: `请求 ${requestResultName} catch 异常` + JSON.stringify(err) })
      $global.mfutil.logger.log(`请求 ${requestResultName} catch 异常` + JSON.stringify(err), 'interfaceRequest');
    }
  })
}

/**
 * 公共方法 : 调用云函数
 * @param {Object} obj 请求数据 
 * 
 * @returns 结果信息
 */
const cloudInvoke = async function (options) {
  let { data, handler,cloudName='' } = options;
  return new Promise(async (resolve, reject) => {
    try {
      const res = await $global.cloud.function.invoke(cloudName || $global.config.cloudName, data, handler);
      resolve(res)
    } catch (err) {
      reject(err)
    }
  })
}

export default { ...httpRequest };